import { defineComponent, nextTick, ref } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { useMessage } from '@/hooks/web/useMessage';
import { useUserStore } from '/@/store/modules/user';
import { uploadFaceApi } from '../service'; // 假设这是你的上传API
import { updateUserApi } from '../../studentInfo/service';

export default defineComponent({
  name: 'UploadFaceModal',
  emits: ['register', 'reload'],
  setup(_, { emit }) {
    const {
      createMessage: { success, error: errorMessage },
    } = useMessage();
    const userStore: any = useUserStore();

    let takePhoto = () => {};
    const faceUrl = ref('');
    const [registerModal, { changeLoading, changeOkLoading, closeModal, setModalProps }] =
      useModalInner(async ({ record, type = 'add' }) => {
        changeLoading(true);
        changeOkLoading(true);
        setModalProps({ title: '认证信息（背景尽量为纯色背景，脸部占据可视区大部分）' });
        faceUrl.value = '';
        const video: any = document.querySelector('#video');
        const canvas: any = document.querySelector('#canvas');
        const ctx: any = canvas.getContext('2d');
        const errorDiv: any = document.querySelector('#error');

        canvas.width = canvas.height = 400;

        try {
          const stream = await navigator.mediaDevices.getUserMedia({
            video: { width: 400, height: 400 },
          });
          video.srcObject = stream;
          video.onloadedmetadata = () => video.play();
        } catch (err) {
          console.error('摄像头访问失败:', err);
          errorDiv.textContent = '无法访问摄像头，请检查设备或权限设置。';
        }

        takePhoto = function capturePhoto() {
          if (!video.srcObject) {
            errorDiv.textContent = '没有检测到摄像头，无法拍照。';
            return;
          }

          ctx.drawImage(video, 0, 0, 400, 400);
          faceUrl.value = canvas.toDataURL('image/png');
          nextTick(() => {
            (document.getElementById('imgXX') as any).src = faceUrl.value;
          });
        };

        changeLoading(false);
        changeOkLoading(false);
      });

    // 将Base64转换为Blob对象
    function dataURLtoBlob(dataurl: string) {
      const arr = dataurl.split(',');
      const mime = arr[0].match(/:(.*?);/)![1];
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    }

    const handleSubmit = async () => {
      changeLoading(true);
      changeOkLoading(true);

      try {
        // 1. 拍照
        takePhoto();
        if (!faceUrl.value) {
          throw new Error('请先拍照');
        }

        // 2. 准备上传数据
        const blob = dataURLtoBlob(faceUrl.value);
        const formData = new FormData();
        formData.append('file', blob, 'face_capture.png');

        // 3. 调用上传接口
        const response = await uploadFaceApi(formData);
        console.log(response);

        await updateUserApi({
          FaceUrl: 'http://api.gamestrial.com/xcx_file/' + response.file.filename,
          UserID: userStore.getUserInfo.UserID,
        });
        if (response.code === 200) {
          await success('人脸照片上传成功，请重新登陆');
          userStore.logout();
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (err: any) {
        errorMessage(err.message || '上传人脸照片失败');
      } finally {
        changeLoading(false);
        changeOkLoading(false);
      }
    };

    return () => (
      <BasicModal
        width={400}
        minHeight={400}
        onRegister={registerModal}
        destroyOnClose
        onOk={handleSubmit}
      >
        <div>
          <div class={faceUrl.value ? 'hidden' : ''}>
            <video id="video" autoplay width="400" height="400"></video>
            <canvas id="canvas" style="display: none;"></canvas>
          </div>
          <div class={faceUrl.value ? '' : 'hidden'}>
            <img id="imgXX" src="" width="400" height="400" />
          </div>
        </div>
        <div id="error" style="color: red; margin-top: 10px;"></div>
      </BasicModal>
    );
  },
});
